package com.msf.tutorial.java8.chapter5;

import com.msf.tutorial.java8.Apple;

import java.util.Comparator;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 复合Lambda表达式
 *
 * 比较器
 * reversed：逆序
 * thenComparing：比较器链
 *
 * 条件操作
 * negate：非
 * and：与
 * or：或
 *
 * 联合
 * andThen：a andThen b  =>  a -> b
 * compose：a compose b  =>  b -> a
 */
public class C01Use {

    /**
     * 顺序
     */
    public static void common() {
        Comparator<Apple> reversed = Comparator.comparing(Apple::getWeight);
    }

    /**
     * 逆序
     */
    public static void reversed() {
        Comparator<Apple> reversed = Comparator.comparing(Apple::getWeight).reversed();
    }

    /**
     * 比较器链
     * 多重排序
     */
    public static void thenComparing() {
        Comparator.comparing(Apple::getWeight).reversed().thenComparing(Apple::getCountry);
    }

    /**
     * negate
     * 非
     */
    public static void negate() {
        Predicate<Apple> redApple = (apple) -> "red".equals(apple.getColor());
        Predicate<Apple> notRedApple = redApple.negate();
    }

    /**
     * and
     * 且
     */
    public static void and() {
        Predicate<Apple> redApple = (apple) -> "red".equals(apple.getColor());
        Predicate<Apple> redAndHeavyApple = redApple.and(a -> a.getWeight() > 150);
    }

    /**
     * or
     * 或
     */
    public static void or() {
        Predicate<Apple> redApple = (apple) -> "red".equals(apple.getColor());
        Predicate<Apple> redAndHeavyAppleOrGreen = redApple.and(a -> a.getWeight() > 150).or(a -> "green".equals(a.getColor()));
    }

    /**
     * andThen
     */
    public static void andThen() {
        Function<Integer, Integer> f = x -> x + 1;
        Function<Integer, Integer> g = x -> x * 2;
        Function<Integer, Integer> h = f.andThen(g);    // g(f(x))
        int result = h.apply(1);    // 返回4
    }

    /**
     * compose
     */
    public static void compose() {
        Function<Integer, Integer> f = x -> x + 1;
        Function<Integer, Integer> g = x -> x * 2;
        Function<Integer, Integer> h = f.compose(g);    // g(f(x))
        int result = h.apply(1);    // 返回4
    }
}
